# _*_ coding: utf-8 _*_
# ---------------------------
# @创建作者：ZQQ
# @创建时间：2025/01/15
# @说明：Docker Compose文件生成器
# ---------------------------

import os
from pathlib import Path
from typing import Dict, Any


class DockerComposeGenerator:
    """Docker Compose文件生成器"""
    
    def __init__(self, template_path: str = "docker-compose.template.yml"):
        """
        初始化生成器
        
        Args:
            template_path: 模板文件路径
        """
        self.template_path = Path(template_path)
        self.template_content = self._load_template()
    
    def _load_template(self) -> str:
        """加载模板文件内容"""
        if not self.template_path.exists():
            raise FileNotFoundError(f"模板文件不存在: {self.template_path}")
        
        with open(self.template_path, 'r', encoding='utf-8') as f:
            return f.read()
    
    def generate_compose_file(self, 
                            model_name: str, 
                            port: int, 
                            ssh_port: int = None,
                            output_path: str = None,
                            **kwargs) -> str:
        """
        生成docker-compose文件
        
        Args:
            model_name: 模型名称
            port: 应用端口
            ssh_port: SSH端口（可选）
            output_path: 输出文件路径（可选）
            **kwargs: 其他参数
            
        Returns:
            生成的docker-compose文件路径
        """
        # 设置默认参数
        params = {
            'MODEL_NAME': model_name,
            'APP_PORT': str(port),
            'HOST_PORT_APP': str(port),
            'HOST_PORT_SSH': str(ssh_port or (port + 1000)),
            'CONTAINER_PORT_SSH': '22',
            'DEBUG': kwargs.get('debug', 'False'),
            'WORKERS': kwargs.get('workers', '4'),
            'TIMEOUT': kwargs.get('timeout', '120'),
        }
        
        # 替换模板中的占位符
        content = self.template_content
        for key, value in params.items():
            content = content.replace(f'{{{{{key}}}}}', str(value))
        
        # 确定输出路径
        if output_path is None:
            output_path = f"{model_name}/docker-compose.yml"
        
        output_path = Path(output_path)
        
        # 确保输出目录存在
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        # 写入文件
        with open(output_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"✅ 已生成docker-compose文件: {output_path}")
        return str(output_path)
    
    def generate_for_project(self, 
                           folder_name: str, 
                           model_name: str, 
                           port: int,
                           **kwargs) -> str:
        """
        为项目生成docker-compose文件
        
        Args:
            folder_name: 项目文件夹名称
            model_name: 模型名称
            port: 端口号
            **kwargs: 其他参数
            
        Returns:
            生成的docker-compose文件路径
        """
        # 项目目录结构: folder_name/folder_name/
        project_dir = Path(folder_name)
        
        # 生成带模型名称和端口号的文件名
        compose_filename = f"docker-compose-{model_name}-{port}.yml"
        output_path = project_dir / compose_filename
        
        return self.generate_compose_file(
            model_name=model_name,
            port=port,
            output_path=str(output_path),
            **kwargs
        )


if __name__ == "__main__":
    # 测试生成器
    generator = DockerComposeGenerator()
    
    # # 生成测试文件
    # test_path = generator.generate_compose_file(
    #     model_name="model",
    #     port=5098,
    #     ssh_port=6000,
    #     debug="True"
    # )
    folder_name = "deploy/deploy"
    model_name = "model"
    port = 5098
    test_path = generator.generate_for_project(
        folder_name=folder_name,
        model_name=model_name,
        port=port,
        debug="True"
    )
    
    print(f"测试文件已生成: {test_path}")
